import router from 'umi/router';
import { login, logOut, hospitalList, departmentList, doctorList } from '../services/global';
import { message } from 'antd';

export default {
  namespace: 'login',
  state: {
    status: undefined,
    departmentList: [],
    hospitalList: [],
    doctorList: [],
    loading: false,
  },

  effects: {
    *login({ payload }, { call, put }) {
      try {
        yield put({
          type: 'changeLoading',
          payload: true,
        });
        const res = yield call(login, payload);
        localStorage.setItem('userName', res.data.userName);
        localStorage.setItem('tokenId', res.data.accessToken);
        localStorage.setItem('resource', JSON.stringify(res.data.resources));
        if (res.data.resources.length === 0) {
          message.error('没有权限!');
        } else {
          let node = res.data.resources[0].childrens[0];
          router.push(`/${node.sup}/${node.path}`);
        }
      } catch (e) {
        message.error(e.message);
      } finally {
        yield put({
          type: 'changeLoading',
          payload: false,
        });
      }
    },

    *logout(_, { put, call }) {
      try {
        yield call(logOut);
        localStorage.clear();
        message.info('退出登录');
        router.push('/login');
      } catch (e) {
        message.info(e.message);
      }
    },
    *hospitalList({ payload }, { call, put }) {
      try {
        const res = yield call(hospitalList, payload);
        yield put({
          type: 'save',
          payload: {
            hospitalList: res.data,
          },
        });
      } catch (e) {
        message.error(e.message);
      }
    },
    *departmentList({ payload }, { call, put }) {
      try {
        const res = yield call(departmentList, payload);
        yield put({
          type: 'save',
          payload: {
            departmentList: res.data,
          },
        });
      } catch (e) {
        message.error(e.message);
      }
    },
    *doctorList({ payload }, { call, put }) {
      try {
        const res = yield call(doctorList, payload);
        yield put({
          type: 'save',
          payload: {
            doctorList: res.data,
          },
        });
      } catch (e) {
        message.error(e.message);
      }
    },
  },

  reducers: {
    changeLoading(state, { payload }) {
          
      return {
        ...state,
        loading: payload,
      };
    },
  },
};
